package com.huhu.controller.base;

import com.huhu.common.util.Logger;
import com.huhu.dto.Result;
import com.huhu.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;

import javax.servlet.http.HttpSession;

/**
 * The type Base controller.
 *
 * Created by huhu on 2016/9/6.
 */
public class BaseController  {

    Logger logger = Logger.getLogger(BaseController.class);

    /**
     * Sets u 2 session.
     *
     * @param httpSession the http session
     * @param user        the user
     */
    protected void setU2Session(HttpSession httpSession, User user) {

        httpSession.setAttribute("user", user);
    }

    /**
     * Is user login boolean.
     *
     * @param httpSession the http session
     * @return the boolean
     */
    protected boolean isUserLogin(HttpSession httpSession) {
        if (httpSession.getAttribute("user") != null) {
            return true;
        }
        return false;
    }

    /**
     * Gets login u.
     *
     * @param httpSession the http session
     * @return the login u
     */
    protected User getLoginU(HttpSession httpSession) {

        return (User) httpSession.getAttribute("user");
    }

    /**
     * Logout.
     *
     * @param httpSession the http session
     */
    protected void logout(HttpSession httpSession) {
        httpSession.setAttribute("user", null);
    }


    @ExceptionHandler({UnauthenticatedException.class})
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    protected Result processUnAuthcException(NativeWebRequest request, UnauthenticatedException ex) {
        Result rst = new Result();
        rst.setFlag(-1);
        rst.setContent("请确认身份！");

        return rst;
    }

    @ExceptionHandler({AuthenticationException.class})
    @ResponseStatus(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED)
    @ResponseBody
    protected Result processAuthcException(NativeWebRequest request, UnauthenticatedException ex) {
        Result rst = new Result();
        rst.setFlag(-1);
        rst.setContent("请确认身份！");

        return rst;
    }

    @ExceptionHandler({UnauthorizedException.class})
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    protected Result processUnAuthzException(NativeWebRequest request, UnauthorizedException ex) {
        Result rst = new Result();
        rst.setFlag(-1);
        rst.setContent("您没有相应权限，请联系管理员！");

        return rst;
    }

}
